import pytest
import os
import json
from typing import Dict, Any
import httpx

# 测试环境URL
BASE_URL = "http://localhost:8080"

# 测试用户信息
TEST_ADMIN_USER = {
    "username": "test_admin",
    "password": "test_password"
}

TEST_WECHAT_USER = {
    "code": "test_wechat_code"  # 这里需要一个有效的微信code，实际测试时需要修改
}

pytest_plugins = ["pytest_asyncio"]

@pytest.fixture
async def api_client():
    """创建测试HTTP客户端"""
    client = httpx.AsyncClient(base_url=BASE_URL, timeout=30.0)
    yield client
    await client.aclose()

@pytest.fixture
async def admin_token(api_client: httpx.AsyncClient) -> str:
    """获取管理员令牌"""
    response = await api_client.post("/auth/admin", json=TEST_ADMIN_USER)
    assert response.status_code == 200
    data = response.json()
    assert data["code"] == 10000
    return data["data"]

@pytest.fixture
async def user_token(api_client: httpx.AsyncClient) -> str:
    """获取用户令牌（此处需模拟，因为实际环境中微信code只能使用一次）"""
    # 在实际测试中，这里需要替换为真实的微信登录逻辑或模拟逻辑
    # 此处仅为示例
    response = await api_client.post("/auth/wechat", json=TEST_WECHAT_USER)
    assert response.status_code == 200
    data = response.json()
    assert data["code"] == 10000
    return data["data"]

@pytest.fixture
def admin_headers(admin_token: str) -> Dict[str, str]:
    """创建带有管理员令牌的headers"""
    return {
        "Authorization": f"Bearer {admin_token}",
        "Content-Type": "application/json"
    }

@pytest.fixture
def user_headers(user_token: str) -> Dict[str, str]:
    """创建带有用户令牌的headers"""
    return {
        "Authorization": f"Bearer {user_token}",
        "Content-Type": "application/json"
    }

def parse_response(response: httpx.Response) -> Dict[str, Any]:
    """解析API响应并验证响应格式"""
    assert response.status_code == 200
    data = response.json()
    assert "code" in data
    assert "data" in data
    return data 